import { Button, Card, Modal, Switch, Table, Upload, message } from "antd";
import React, { useEffect, useState } from "react";
import { PlusOutlined, LoadingOutlined } from "@ant-design/icons";
import {
  reqAddTrad,
  reqDeteTradeItem,
  reqGetTradItem,
  reqTradeList,
  reqUpdataTrad,
} from "@/api/goods";
import { IRecord } from "@/types/trade";

import type {
  RcFile,
  UploadChangeParam,
  UploadFile,
  UploadProps,
} from "antd/es/upload/interface";
import Input from "antd/lib/input/Input";
//#region 上传文件
const getBase64 = (img: RcFile, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result as string));
  
  reader.readAsDataURL(img);
};

// 图片上传之前，点击上传用户头像，并使用 beforeUpload 限制用户上传的图片格式和大小。
// beforeUpload 的返回值可以是一个 Promise 以支持异步处理，如服务端校验等
const beforeUpload = (file: RcFile) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    message.error("上传图片格式为jpeg或png");
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("图片大小不能超过2MB");
  }
  return isJpgOrPng && isLt2M;
};
//#endregion

export default function GoodsList() {
  // 定义变量控制展示新增还是编辑
  const [isEdit, setIsedit] = useState(false);

  // 样式提示条
  const [messageApi, contextHolder] = message.useMessage();
  //#region 请求列表数据部分

  const columns: any = [
    {
      title: "序号",
      dataIndex: "id",
      // key: "id",
      render(a:any,b:any,index:number){
        return <span>{index+1}</span>
      }
    },
    {
      title: "名称",
      dataIndex: "tmName",
      key: "tmNam",
    },
    {
      title: "LOgo",
      dataIndex: "address",
      render(text: any, record: any, index: any) {
        return <img src={record.logoUrl} alt="" style={{ width: 100 }} />;
      },
    },
    {
      title: "操作",
      dataIndex: "address",
      render(row: IRecord, data: any, index: string) {
        return (
          <div>
            <Button type="primary" onClick={showModal("edit", data)}>
              修改
            </Button>
            <Button type="dashed" className="left" onClick={toDelet(data)}>
              删除
            </Button>
          </div>
        );
      },
    },
  ];

  // 定义状态
  let [page, setPage] = useState(1);
  let [total,setTotal]=useState(0)
  let [limit, setLimit] = useState(5);
  // 定义品牌列表数据
  const [tradList, setTradList] = useState<IRecord[]>();

  // 定义删除品牌列表
  const toDelet = (data: IRecord) => {
    return async () => {
      // 拿到id
      const id = data.id;
      const res = await reqDeteTradeItem(data.id as number);
      if (res.code === 200) {
        messageApi.info("删除成功");
      }
      // 删除成功
      getTradList();
      // 重新请求列表数据
    };
  };

  // 定义获取品牌列表的方法
  const getTradList = async () => {
        const res = await reqTradeList(page, limit);
      setTradList(res.data.records);
      setTotal(res.data.total)
  };

  useEffect(() => {
  getTradList()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [page, limit]);
  //#endregion

  //#region 点击新增弹出框

  const [isModalOpen, setIsModalOpen] = useState(false);
  // 定义品牌名称
  const [name, setName] = useState("");
    const [logoUrl,setLogoUrl]=useState('')
    const [id,setId]=useState('')

  //定义获取单个品牌的方法
  const getTradItem = async (id: string) => {
    const res = await reqGetTradItem(id);
    if (res.code === 200) {
      // 获取成功
      setName(res.data.tmName);
      setImageUrl(res.data.logoUrl);
    }
  };

  //  展示弹出框
  const showModal = (type: any, data?: any) => {
    return () => {
      if (type === "add") {
        setIsedit(false);
      } else if (type === "edit") {
        // 点击编辑数据回显
        setId(data.id)
        getTradItem(data.id);
        setIsedit(true);
      }
      setIsModalOpen(true);
    };
  };

  // 点击确定

  const handleOk = async () => {
    if(name===''||logoUrl===''){
      console.log(1);
      
   messageApi.error('品牌名称和品牌logo不能为空')
      return
    }
    // 收集参数上传品牌
    // 收集参数
    const params = {
      tmName: name,
      logoUrl,
    };
    const res =isEdit?await reqUpdataTrad({...params,id}):await reqAddTrad(params);
    // setIsModalOpen(false);
    // 上传成功
    if(res.code){
      setIsModalOpen(false);
      // 重新请求列表数据
      getTradList()
    }
  // 清空表单数据
  setName('')
   setImageUrl('')
  };

  // 点击取消
  const handleCancel = () => {
     messageApi.open({
      type: 'warning',
      content: '取消上传',
      duration: 10,
    });
      // 清空表单数据
  setName('')
   setImageUrl('')
    setIsModalOpen(false);
  };

  // 设置输入框的品牌名称
  const toSetValue = (e: any) => {
    // console.log(e);
    setName(e.target.value);
  };
  //#endregion

  //#region 弹出框上传图片
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();
  // const [newImg,setNewImg]=useState()

  const handleChange: UploadProps["onChange"] = (
    info: UploadChangeParam<UploadFile>
  ) => {
    // 上传状态正在上传
    if (info.file.status === "uploading") {
      setLoading(true);
      return;
    }
    // 上传成功
    if (info.file.status === "done") {
      getBase64(info.file.originFileObj as RcFile, (url) => {
        console.log(info);
setLogoUrl(info.file.response.data)
        setLoading(false);
        // 设置显示的图片
        setImageUrl(url);
        return;
      });
    }
    if (info.file.status === "error") {
      // 上传失败
      messageApi.info("上传失败");
      setLoading(false);
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );
  //#endregion
  return (
    <Card className="left top">
      {contextHolder}
      <Button type="primary" icon={<PlusOutlined />} onClick={showModal("add")}>
        新增
      </Button>
      <Table
        pagination={{
          total,
          pageSize: limit,
          current: page,
           showQuickJumper: true,
            showSizeChanger: true,
            showTotal: (total: number) => {
              return <span>总计：{total}</span>
            },
            onChange(page: number, pageSize: number) {
              setPage(page)
              setLimit(pageSize)
            }
          
        }}
        rowKey={"id"}
        dataSource={tradList}
        columns={columns}
        bordered
        className="top"
      />

      {/* 弹出框 */}
      {
        <Modal
          title={isEdit ? "新增品牌" : "编辑品牌"}
          open={isModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}
        >
          品牌名称：
          <Input
            value={name}
            placeholder="Basic usage"
            style={{ width: 350 }}
            onChange={toSetValue}
          />
          {/* 图片上传 */}
          <br />
          品牌图片：
          <Upload
     
            listType="picture-card"
            className="avatar-uploader top"
            showUploadList={false}
            action="http://sph-h5-api.atguigu.cn/admin/product/upload"
            beforeUpload={beforeUpload}
            onChange={handleChange}
          >
            {imageUrl ? (
              <img src={imageUrl} alt="avatar" style={{ width: "100%" }} />
            ) : (
              uploadButton
            )}
          </Upload>
        </Modal>
      }
    </Card>
  );
}
